package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wenmedia.dtos.WmMaterialDTO;
import com.heima.model.wenmedia.pojos.WmMaterial;
import com.heima.model.wenmedia.pojos.WmNewsMaterial;
import com.heima.model.wenmedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
@Slf4j
public class WmMaterialServiceimpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
     private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //1.参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确得文件");
        }
        //当前线程中获取用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请登录");
        }
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(originalFilename)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确得素材格式,[jpg,jpeg,png,gif]");
        }
        //2 上传oss
        String fileId=null;
        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId = fileStorageService.store(prefix, filename, suffix, multipartFile.getInputStream());
            log.info("阿里云oss文件 fileid:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error{}",e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"服务器繁忙请稍后重试");
        }
        WmMaterial wmMaterial = new WmMaterial();
        //封装是否收藏
        wmMaterial.setIsCollection((short)0);
        //封装素材类型
        wmMaterial.setType((short)0);
        //封装创建时间
        wmMaterial.setCreatedTime(new Date());
        //设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        //前端显示
        wmMaterial.setUrl(webSite+fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findlist(WmMaterialDTO dto) {
        //校验分页参数
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        //查询是否收藏
        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //当前用户素材
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
         throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH,"无权操作");
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());
        //时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> iPage = page(page, wrapper);
        List<WmMaterial> pageRecords = iPage.getRecords();
        for (WmMaterial record : pageRecords) {
            record.setUrl(webSite+record.getUrl());
        }
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal());
        pageResponseResult.setData(pageRecords);
        return pageResponseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        //查询当前id是否被引用
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不允许此操作");
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getId,id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if(count>0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不允许此操作");
        }
        //删除数据库
        removeById(id);
        //删除oss
        fileStorageService.delete(wmMaterial.getUrl());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不允许此操作");
        }
        //获取当前用户信息
        WmUser user = WmThreadLocalUtils.getUser();
        Integer userId = user.getId();
        if(!wmMaterial.getUserId().equals(userId)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只能收藏自己得作品");
        }
        wmMaterial.setIsCollection(type);
        updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    private boolean checkFileSuffix(String path) {
        if (StringUtils.isBlank(path)) {
            return false;
        }
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAll = false;
        for (String suffix : allowSuffix) {
            //此方法测试字符串是否以指定的后缀 suffix 结束。
            if (path.endsWith(suffix)) {
                isAll = true;
                break;
            }
        }
        return isAll;
    }
}
